package com.zzu.chat.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuexiang.xui.adapter.simple.AdapterItem;
import com.xuexiang.xui.widget.popupwindow.popup.XUISimplePopup;
import com.xuexiang.xutil.display.DensityUtils;
import com.zzu.chat.R;
import com.zzu.chat.bean.SmallLabel;
import com.zzu.chat.bean.Task;
import com.zzu.chat.task.TaskAdapter;
import com.zzu.chat.util.TimeUtils;

import org.litepal.LitePal;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.leancloud.AVObject;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class TimeActivity extends AppCompatActivity implements CalendarView.OnCalendarSelectListener{


    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.calendarLayout)
    CalendarLayout calendarLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.add_time_list_float_button)
    FloatingActionButton addTimeListFloatButton;

    String finishedTime = "";   //开始时间
    String endTime="";      //结束时间

    private XUISimplePopup mPriorityPopup; //优先级
    int priority;
    private XUISimplePopup mLabelPopup; //标签
    String label = "";

    Date finishedDate;

    String finishedMonth = "";

    /**
     * 点击添加时出现的输入框
     */
    private BottomSheetDialog dialog;

    private List<Task> taskList = new ArrayList<>();

    private TaskAdapter taskAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time);
        ButterKnife.bind(this);
        // 更换标题
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        try {
            finishedDate = TimeUtils.getNowDateWithOutHour();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //日历初始化
        initView();
        initCalendarView();

        initListener();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what== 0x11){
                 List<Task> tasks = (List<Task>) msg.getData().getSerializable("taskList");
                System.out.println("handlerTask:"+tasks.size());
            }
        }
    };

    private void initCalendarView() {
        final int year = calendarView.getCurYear();
        final int month = calendarView.getCurMonth();
        Map<String, Calendar> map = new HashMap<>();
        for (int j = 5; j < 10; j++) {
            map.put(getSchemeCalendar(year, month, j, Color.RED).toString(), getSchemeCalendar(year, month, j, Color.RED));
        }
        for (int i = 10; i < 28; i++) {
            map.put(getSchemeCalendar(year, month, i, Color.TRANSPARENT).toString(), getSchemeCalendar(year, month, i, Color.TRANSPARENT));
        }
        calendarView.setSchemeDate(map);
    }

    public Calendar getSchemeCalendar(int year, int month, int day, int color) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        return calendar;
    }


    private void initView(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        initList();
        taskAdapter = new TaskAdapter(taskList);
        recyclerView.setAdapter(taskAdapter);

        MyThread myThread = null;
        try {
            myThread = new MyThread(TimeUtils.getNowDateWithOutHour());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        myThread.start();
    }


    private void initListener(){
        calendarView.setOnCalendarSelectListener(this);


        // 刷新
       refreshLayout.setOnRefreshListener(new OnRefreshListener() {
           @Override
           public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initList();
                taskAdapter = new TaskAdapter(taskList);
                recyclerView.setAdapter(taskAdapter);
                refreshLayout.finishRefresh();
           }
       });
        refreshLayout.autoRefresh();


        //悬浮按钮
        addTimeListFloatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("floatButton");
                showTaskDialog();
            }
        });
    }


    /**
     * by moos on 2018/04/20
     * func:弹出添加输入框框
     */
    private void showTaskDialog() {

        initListPopup();
        initPrioprityPopup();
        dialog = new BottomSheetDialog(TimeActivity.this);
        View taskAddView = LayoutInflater.from(TimeActivity.this).inflate(R.layout.add_time_list_dialog_layout, null);    //底部弹出框加载的布局
        final EditText taskContentText = (EditText) taskAddView.findViewById(R.id.dialog_task_comment);             //任务内容输入框
        final ImageButton alarmButton = (ImageButton) taskAddView.findViewById(R.id.dialog_alarm_time_button);   //时间选择按钮
        final ImageButton priorityButton = (ImageButton) taskAddView.findViewById(R.id.dialog_priority_button);  //优先级按钮
        final ImageButton labelButton = (ImageButton) taskAddView.findViewById(R.id.dialog_label_button);        //标签按钮
        final ImageButton endAlarmButton = (ImageButton) taskAddView.findViewById(R.id.dialog_end_time_button);

        final Button taskAddButton = (Button) taskAddView.findViewById(R.id.dialog_task_add);
        dialog.setContentView(taskAddView);


        /**
         * 解决bsd显示不全的情况
         */
        View parent = (View) taskAddView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        taskAddView.measure(0, 0);
        behavior.setPeekHeight(taskAddView.getMeasuredHeight());

        //时间按钮选择计划开始时间
        alarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePickerDialog(TimeActivity.this, DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, view, java.util.Calendar.getInstance());
            }
        });

        //结束时间按钮选择计划结束时间
        endAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (finishedTime == "" || finishedTime == null){
                    Toast.makeText(TimeActivity.this, "请先选择开始时间", Toast.LENGTH_SHORT).show();
                }else {
                    showEndTimePickerDialog(TimeActivity.this, DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, view, java.util.Calendar.getInstance());
                }

            }
        });

        // 优先级按钮选择优先级
        priorityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPriorityPopup.showUp(view);
            }
        });

        // 标签按钮选择标签
        labelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLabelPopup.showUp(view);
            }
        });

        // 添加按钮 提交 将添加的任务 添加到集合中
        taskAddButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String taskContentString = taskContentText.getText().toString().trim();

                if (TextUtils.isEmpty(taskContentString)) {
                   Toast.makeText(TimeActivity.this, "添加内容不能为空", Toast.LENGTH_SHORT).show();
                } else if (finishedTime.equals("") || finishedTime == null) {
                    Toast.makeText(TimeActivity.this, "请选择计划时间", Toast.LENGTH_SHORT).show();
                } else if (label.equals("") || label == null) {
                    Toast.makeText(TimeActivity.this, "请选择标签", Toast.LENGTH_SHORT).show();
                }else if (endTime.equals("") || endTime == null) {
                    Toast.makeText(TimeActivity.this,"请选择计划结束时间", Toast.LENGTH_SHORT).show();
                } else if (priority == 0) {
                    priority = 1;
                } else {
                    dialog.dismiss();

                    Task task = new Task();
                    task.setFinishedTime(finishedTime);
                    task.setEndTime(endTime);
                    task.setFinished(false);
                    task.setTaskContent(taskContentString);
                    task.setLabel(label);
                    task.setPriority(priority);
                    task.setFinishedDate(finishedDate);

                    taskList.add(task);
                    taskAdapter.notifyDataSetChanged();


                    addTaskToSQL(task);
                    uploadTask(task);
                    label = "";
                    priority = 0;
                    finishedTime = "";
                    endTime = "";
                    Toast.makeText(TimeActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
                }
            }
        });
        taskContentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }

    //选择开始时间 时分秒
    public void showTimePickerDialog(Context context, int themeResId, final View tv, java.util.Calendar calendar) {
        new TimePickerDialog(context
                , themeResId
                , (view, hourOfDay, minute) -> {

            if (minute<10){
                finishedTime = hourOfDay + ":0" + minute;
            }else {
                finishedTime = hourOfDay + ":" + minute;
            }
        }
                // 设置初始日期
                , calendar.get(java.util.Calendar.HOUR_OF_DAY)
                , calendar.get(java.util.Calendar.MINUTE)
                , false)
                .show();
    }
    //选择结束时间 时分秒
    public void showEndTimePickerDialog(Context context, int themeResId, final View tv, java.util.Calendar calendar) {
        new TimePickerDialog(context
                , themeResId
                , (view, hourOfDay, minute) -> {

            if (minute <10){
                endTime = hourOfDay + ":0" + minute;
            }else {
                endTime = hourOfDay + ":" + minute;
            }


        }       // 设置初始日期
                , calendar.get(java.util.Calendar.HOUR_OF_DAY)
                , calendar.get(java.util.Calendar.MINUTE)
                , false)
                .show();
    }

    // 优先级按钮 弹出框初始化
    //优先级初始化
    public static AdapterItem[] menuItems = new AdapterItem[]{
            new AdapterItem("高优先级", R.drawable.ic_add_time_list_priority3),
            new AdapterItem("中优先级", R.drawable.ic_add_time_list_priority2),
            new AdapterItem("低优先级", R.drawable.ic_add_time_list_priority1),
    };
    private void initPrioprityPopup() {
        mPriorityPopup = new XUISimplePopup(TimeActivity.this, menuItems)
                .create((adapter, item, position) ->
                {
                   Toast.makeText(TimeActivity.this, item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                    priority = 4 - position;    //设置优先级

                });
    }

    //标签按钮 弹出框初始化
    private void initListPopup() {
        List<SmallLabel> smallLabelList = LitePal.findAll(SmallLabel.class);
        int length = smallLabelList.size();
        String s[] = new String[length];
        for (int i = 0; i< length; i++){
            s[i] = smallLabelList.get(i).getName();
        }
        mLabelPopup = new XUISimplePopup(TimeActivity.this, s)
                .create(DensityUtils.dip2px(TimeActivity.this, 170), (adapter, item, position) ->
                {
                    Toast.makeText(TimeActivity.this,item.getTitle().toString(),Toast.LENGTH_SHORT).show();
                    label = item.getTitle().toString();
                })
                .setHasDivider(true);
    }

    private void addTaskToSQL(Task task){
        task.save();
    }

    class MyThread extends Thread{
        private Date date;
        public MyThread(Date date){
            this.date = date;
        }
        @Override
        public void run() {
            super.run();
            System.out.println("date:"+date.getTime());
            List<Task> taskList3 =  LitePal.where("finishedDate=?", String.valueOf(date.getTime()))
                    .order("finishedTime")
                    .find(Task.class);
            System.out.println("taskThreadSize:"+taskList3.size());
            // 通过Handler传递到UI线程中
            Message message = new Message();
            message.what = 0x11;
            Bundle bundle = new Bundle();

            bundle.putSerializable("taskList", (Serializable) taskList3);

            message.setData(bundle);
            handler.sendMessage(message);
        }
    }

    private void initList() {
        taskList.clear();
        long date = finishedDate.getTime();
        taskList =  LitePal.where("finishedDate=?", String.valueOf(date))
                .order("finishedTime")
                .find(Task.class);

    }

    /**
     * 上传到云数据库
     * @param task
     */
    private void uploadTask(Task task) {
        AVUser user = AVUser.getCurrentUser();
        if (user != null) {
            AVObject object = new AVObject("Task");
            object.put("finishedDate", task.getFinishedDate());
            object.put("finishedTime", task.getFinishedTime());
            object.put("endTime", task.getEndTime());
            object.put("label", task.getLabel());
            object.put("priority", task.getPriority());
            object.put("taskContent", task.getTaskContent());
            object.put("isFinished", task.isFinished());
            object.put("finishedMonth", task.getFinishedMonth());
            object.saveInBackground().subscribe(new Observer<AVObject>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(AVObject object) {
                    Log.d("uploadTask", "success");
                }

                @Override
                public void onError(Throwable e) {
                    Log.d("uploadTask", "fail");
                }

                @Override
                public void onComplete() {

                }
            });
        }
    }
    // 其他活动启动该活动
    public static void actionStart(Context context) {
        Intent intent = new Intent(context, TimeActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        if (isClick) {
            if (calendarLayout.isExpand()) {
                calendarLayout.shrink();
            }
        }
        String s = calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay();

        try {
            finishedDate = TimeUtils.getDateFromStringWithoutHour(s);
            initList();
            taskAdapter.notifyDataSetChanged();
            refreshLayout.autoRefresh();
            refreshLayout.finishRefresh();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}
